package alvarodelrosal.chat.server.modelo.chataction;

import alvarodelrosal.chat.server.infraestructura.ChatPersistenceManager;
import alvarodelrosal.chat.server.modelo.ChatConnection;
import alvarodelrosal.chat.server.modelo.ChatUser;
import java.util.List;

public class ChatNewUser implements ChatAction {

    @Override
    public String getName() {
        return "NewUser";
    }

    @Override
    public boolean needsAdminPrivileges() {
        return false;
    }

    @Override
    public boolean needsLogin() {
        return false;
    }

    @Override
    public String doAction(ChatConnection connection, List<String> parameters) {
        String username = parameters.get(0);
        String password = parameters.get(1);
        String confirmation = parameters.get(2);
        String name = parameters.get(3);
        String mail = parameters.get(4);
        boolean isAdmin = Boolean.parseBoolean(parameters.get(5));

        if (ChatPersistenceManager.getPersistenceManager().existsTheUser(username)) {
            return "NewUser<:@:>1";
        } else if (!password.equals(confirmation)) {
            return "NewUser<:@:>2";
        } else if (!mail.matches(".+@.+\\.[a-z]+")) {
            return "NewUser<:@:>3";
        } else {
            ChatUser user = new ChatUser(0, username, password, name, mail, isAdmin);
            ChatPersistenceManager.getPersistenceManager().addUser(user);
            return "NewUser<:@:>0";
        }
    }
}
